package com.shsxt.crm.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shsxt.common.util.MathUtil;
import com.shsxt.common.util.Result;
import com.shsxt.crm.dao.YgCustomerDao;
import com.shsxt.crm.dao.YgDataDicDao;
import com.shsxt.crm.model.YgCustomer;
import com.shsxt.crm.model.YgDataDic;
import com.shsxt.crm.service.ICustomerService;

@Service
public class CustomerServiceImpl implements ICustomerService {

	@Autowired
	private YgCustomerDao customerDao;

	@Autowired
	private YgDataDicDao ygDataDicDao;

	@Override
	public List<YgCustomer> queryAllCustomers() {
		Map<String, Object> params = new HashMap<>();
		params.put("isValid", 1);
		List<YgCustomer> list = customerDao.find(params);
		return list;
	}

	@Override
	public Map<String, Object> queryCustomersByParams(YgCustomer ygCustomer) {

		// 设置 分页参数
		PageHelper.startPage(ygCustomer.getPage(), ygCustomer.getRows());
		// 查询分页数据
		Map<String, Object> params = new HashMap<>();
		params.put("khno", ygCustomer.getKhno());
		params.put("name", ygCustomer.getName());
		params.put("isValid", 1);
		List<YgCustomer> info = customerDao.find(params);
		PageInfo<YgCustomer> pageInfo = new PageInfo<>(info);

		// 组装返回数据
		Map<String, Object> map = new HashMap<>();
		map.put("total", pageInfo.getTotal());
		map.put("rows", pageInfo.getList());
		return map;
	}

	@Override
	public List<YgDataDic> queryDataDicValueByDataDicName(String dataDicName) {
		return ygDataDicDao.queryDataDicValueByDataDicName(dataDicName);
	}

	@Override
	@Transactional
	public Result insertCustomerInfo(YgCustomer customer) {

		// 生成 客户编号
		customer.setKhno(MathUtil.genereateKhCode());
		customer.setCreateDate(new Date());
		customer.setUpdateDate(new Date());
		customer.setIsValid(1);// 未删除
		customer.setState(0);
		long ste = customerDao.saveSte(customer);
		if (ste == 1) {
			return Result.success("添加客户成功");
		}
		return Result.fail("添加客户失败");
	}

	@Override
	@Transactional
	public Result updateCustomerInfo(YgCustomer customer) {

		customer.setUpdateDate(new Date());
		long ste = customerDao.updateSte(customer);
		if (ste == 1) {
			return Result.success("更新客户成功");
		}
		return Result.fail("更新客户失败");
	}

	@Override
	@Transactional
	public Result deleteCustomerInfo(Integer[] ids) {

		List<YgCustomer> list = new ArrayList<>();

		for (Integer temp : ids) {
			YgCustomer customer = new YgCustomer();
			customer.setId(temp);
			list.add(customer);
		}
		customerDao.deleteCustomerInfo(list);

		return Result.success("删除成功 ");
	}

	@Override
	public YgCustomer get(Integer id) {
		return 	customerDao.get(id);
	}
}
